import axios from 'axios'
import { MessageBox, Message, Loading } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import qs from 'qs'
// create an axios instance
// process.env.VUE_APP_BASE_API_HTTP +
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API_HTTP + process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})
// 请求拦截器
service.interceptors.request.use(
  config => {
    // 在发送之前做些什么
    if (config.typeData != 'JSON') {
      config.data = qs.stringify(config.data)
    }
    config.headers['Content-Type'] =
      config.typeData == 'JSON'
        ? 'application/json'
        : 'application/x-www-form-urlencoded'
    config.headers['Access-Control-Allow-Origin'] = '*'
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // 请求错误
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const { code, message } = response.data
    if (code !== 200) {
      // 登录状态失效,重定向登录页
      if (code === 40100) {
        MessageBox.confirm('您的登录状态已失效，请重新登录', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
        // code 10000 为营期孩子发送评分或风采失败
      } else if (code === 10000) {
        return Promise.reject(response.data)
      } else {
        Message({
          message: message || '网络异常！',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(message || '网络异常！')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: '网络异常！',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject('网络异常！')
  }
)

export default service
